package org.ourgrid.common.statistics.control;

import java.util.List;

import org.ourgrid.common.LoginResult;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.statistics.util.hibernate.HibernateUtil;
import org.ourgrid.peer.business.dao.PeerDAOFactory;
import org.ourgrid.peer.business.dao.statistics.LoginDAO;
import org.ourgrid.peer.business.util.LoggerUtil;
import org.ourgrid.peer.to.PeerUser;

public class LoginControl {
	
	private static LoginControl instance = null;
	
	public static LoginControl getInstance() {
		if (instance == null) {
			instance = new LoginControl();
		}
		return instance;
	}
	
	public void login(List<IResponseTO> responses, PeerUser peerUser,  LoginResult loginResult, String myUserAtServer, String myCertSubjectDN,
			String description, String email, String label, String latitude, String longitude) {
		responses.add(LoggerUtil.enter());
		
		HibernateUtil.beginTransaction();
		
		try {
			getLoginDAO().login(responses, peerUser, loginResult, myUserAtServer, myCertSubjectDN, description, email, label, latitude, longitude);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		responses.add(LoggerUtil.leave());
	}
	
	public void localConsumerFailure(List<IResponseTO> responses, PeerUser user) {
		responses.add(LoggerUtil.enter());
		
		HibernateUtil.beginTransaction();

		try {
			getLoginDAO().localConsumerFailure(responses, user);
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		responses.add(LoggerUtil.leave());
	}

	public void clearLogins(List<IResponseTO> responses, String myUserAtServer) {
		responses.add(LoggerUtil.enter());
		
		HibernateUtil.beginTransaction();

		try {
			Long peerLastUptime = PeerDAOFactory.getInstance().getPeerDAO().getPeerLastUptime(responses, myUserAtServer);
			if (peerLastUptime == null) {
				peerLastUptime = System.currentTimeMillis();
			}
			getLoginDAO().clearLogins(responses, peerLastUptime);
			
			HibernateUtil.commitTransaction();
		} catch (Exception e) {
			HibernateUtil.rollbackAndCloseSession();
		}
		
		responses.add(LoggerUtil.leave());
		
	}
	
	private LoginDAO getLoginDAO() {
		return PeerDAOFactory.getInstance().getLoginDAO();
	}

}
